package com.ptu.servlet;

import com.google.gson.Gson;
import com.ptu.entity.Dept;
import com.ptu.entity.Employee;
import com.ptu.entity.PageTools;
import com.ptu.entity.Position;
import com.ptu.service.DeptService;
import com.ptu.service.EmployeeService;
import com.ptu.service.PositionService;
import com.ptu.service.impl.DeptServiceImpl;
import com.ptu.service.impl.EmployeeServiceImpl;
import com.ptu.service.impl.PositionServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;
import java.util.List;

/**
 *
 */
@WebServlet("/ptu/EmployeeServlet")
public class EmployeeServlet extends BaseServlet {

    private EmployeeService empService = new EmployeeServiceImpl();

    private DeptService deptService = new DeptServiceImpl();

    private PositionService posService = new PositionServiceImpl();

    // ajax 查询部门岗位上级操作
    protected void empFindMgr(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Employee> mgr = empService.findMgr();
        String mgrJson = new Gson().toJson(mgr);
        resp.getWriter().print(mgrJson);
    }

    // 用户注销
    protected void empLogout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 注销当前的 Session
        req.getSession().invalidate();
        // 2. 跳转到登录界面
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }

    // 用户的登录操作
    protected void empLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取页面数据
        String empid = req.getParameter("empid");
        String pwd = req.getParameter("pwd");

        /***********验证码的校验********************/

        // [1] 获得用户自己输入的验证码
        String yzm = req.getParameter("yzm");

        // [2] 获得系统产生的验证码
        String randStr = (String) req.getSession().getAttribute("randStr");

        if (yzm == null || "".equals(yzm) || !randStr.equals(yzm)) {
            req.setAttribute("yzmMsg", "验证码输入错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }

        // 2. 对数据进行处理
        Employee emp = empService.findEmpByEmpid(empid);
        if(emp != null) {
            if(emp.getPassword().equals(pwd)) {
                HttpSession session = req.getSession();
                session.setAttribute("emp", emp);
                resp.sendRedirect(req.getContextPath() + "/main.html");
                return ;
            }
            req.setAttribute("msg1", "密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }
        req.setAttribute("msg2", "用户不存在");
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }

    // 查询部门岗位上级操作
    protected void findDEM(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Employee> mgrList = empService.findMgr();
        List<Dept> deptList = deptService.findAll();
        List<Position> posList = posService.selectAll();

        req.setAttribute("mgrList", mgrList);
        req.setAttribute("deptList", deptList);
        req.setAttribute("posList", posList);
    }

    // 修改密码
    private void empPwdChange(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String newPwd = req.getParameter("newPwd");
        String oldPwd = req.getParameter("oldPwd");

        Employee emp = (Employee) req.getSession().getAttribute("emp");

        if(emp.getPassword().equals(oldPwd)) {
            empService.changePwd(emp.getEmpId(), newPwd);
            empLogout(req, resp);
        }else {
            req.setAttribute("pwdMsg", "密码不一致");
            req.getRequestDispatcher("/myPwd.jsp").forward(req, resp);
        }
    }

    // 重置密码
    private void empPwdReset(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String empId = req.getParameter("empId");
        String newPwd = "123456";
        int i = empService.changePwd(empId, newPwd);
        if(i > 0) {
            empLogout(req, resp);
        } else {
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

    // 修改员工操作
    protected void empChange(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 接受页面中的数据
        Employee emp = createEmp(req, resp);

        // 2. 数据的处理
        int change = empService.changeEmp(emp);

        // 3. 给用户做出响应
        if (change > 0) {
            resp.sendRedirect(req.getContextPath() + "/ptu/EmployeeServlet?method=showEmpPage");
        } else {
            req.setAttribute("msg", "修改失败");
            req.getRequestDispatcher("/empUpdate.jsp").forward(req, resp);
        }
    }

    // 查询指定员工操作
    protected void empFindOne(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取前端数据
        String empId = req.getParameter("empId");
        String bName = req.getParameter("btu");

        // 2. 数据处理
        Employee emp = empService.findEmpByEmpid(empId);

        // 3. 返回结果
        if (emp != null) {
            req.setAttribute("emp", emp);
            if (bName.equals("1")) { //跳转到用户信息界面
                req.getRequestDispatcher("/empInfo.jsp").forward(req, resp);
            } else {    //跳转到用户信息修改界面
                findDEM(req, resp);
                req.getRequestDispatcher("/empUpdate.jsp").forward(req, resp);
            }
        }
    }

    // 分页查询员工
    public void showEmpPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 第一次访问的验证，如果没有传递参数，设置默认值
        String pageSizeReq = req.getParameter("pageSize");

        int pageSize = 2;   // 查询大小
        if(pageSizeReq != null && !pageSizeReq.equals("")){
            pageSize = Integer.parseInt(pageSizeReq);
        }

        String pageNumberStr = req.getParameter("pageNumber");
        int pageNumber = 1; // 开始值
        if(pageNumberStr!=null&&!pageNumberStr.equals("")){
            pageNumber = Integer.parseInt(pageNumberStr);
        }

        // 分页查询
        PageTools<Employee> empAll = empService.findEmpAll(pageSize, pageNumber);

        // 查询所有部门信息
        List<Dept> deptList = deptService.findAll();

        req.setAttribute("deptList", deptList);
        req.setAttribute("empAll", empAll);

        req.getRequestDispatcher("/empList.jsp").forward(req, resp);
    }

    // 删除指定员工操作
    protected void employeeRemove(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String empid = req.getParameter("empid");
        int i = empService.removeEmp(empid);
        req.setAttribute("i", i);
        showEmpPage(req, resp);
    }

    // 查询指定员工操作
    protected void employeeFindMore(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 接受页面的数据
        String empid = req.getParameter("empid");

        Integer deptno = toInteger(req.getParameter("deptno"));

        Integer onduty = toInteger(req.getParameter("onduty"));

        // 2. 数据的处理

        // 查询符和条件集合
        List<Employee> list = empService.findEmpMore(empid, deptno, onduty);
        PageTools<Employee> empAll = new PageTools<>();
        empAll.setList(list);

        // 查询所有部门信息
        List<Dept> deptList = deptService.findAll();
        req.setAttribute("deptList", deptList);

        // 3. 给用户做出响应
        req.setAttribute("empid", empid);
        req.setAttribute("deptno", deptno);
        req.setAttribute("empAll", empAll);

        req.getRequestDispatcher("/empList.jsp").forward(req, resp);
    }

    // 添加员工处理
    protected void employeeSave(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 接受页面的数据
        Employee emp = createEmp(req, resp);

        // 2. 数据的处理
        int save = empService.addEmp(emp);

        // 3. 给用户做出响应
        if (save > 0) {
            resp.sendRedirect(req.getContextPath() + "/ptu/EmployeeServlet?method=showEmpPage");
        } else {
            req.setAttribute("msg", "添加失败");
            req.getRequestDispatcher("/empAdd.jsp").forward(req, resp);
        }
    }

    // 创建 Employee 对象
    private Employee createEmp(HttpServletRequest req, HttpServletResponse resp) {

        String empId = req.getParameter("empId");

        String password = req.getParameter("password");

        Integer deptno = toInteger(req.getParameter("deptno"));

        Integer posid = toInteger(req.getParameter("posid"));

        String mgrid = req.getParameter("mgrid");

        String realName = req.getParameter("realName");

        String sex = req.getParameter("sex");

        java.sql.Date birthDate = toDate(req.getParameter("birthDate"));

        java.sql.Date hireDate = toDate(req.getParameter("hireDate"));

        java.sql.Date leaveDate = toDate(req.getParameter("leaveDate"));

        Integer onDuty = toInteger(req.getParameter("onDuty"));

        Integer empType = toInteger(req.getParameter("empType"));

        String phone = req.getParameter("phone");

        String qq = req.getParameter("qq");

        String emerContactPerson = req.getParameter("emerContactPerson");

        String idCard = req.getParameter("idCard");

        Employee emp = new Employee(empId, password, deptno, posid, mgrid,
                realName, sex, birthDate, hireDate, leaveDate,
                onDuty, empType, phone, qq, emerContactPerson,
                idCard);

        return emp;
    }

    private Integer toInteger(String value) {
        try {
            return Integer.parseInt(value);
        }catch (NumberFormatException n) {
            return null;
        }
    }

    private Date toDate(String value) {
        try {
            return Date.valueOf(value);
        }catch (IllegalArgumentException i) {
            return null;
        }
    }
}
